package com.us.proframe.controller;

import com.us.proframe.model.knowledge.SysUser;
import com.us.proframe.service.knowledge.SysUserService;
import com.us.proframe.utils.RandomValidateCodeUtil;
import com.us.proframe.utils.ResultUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;


/**
 * 处理登录业务
 * User: lyh
 * Date: 2017/8/2
 * Time: 15:56
 */

@Controller
public class LoginController {

    private final static Logger LOGGER = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private SysUserService sysUserService;
    /**
     * 处理登录逻辑
     * */
    @RequestMapping(value="/tologin")
    public String toLogin(){
        LOGGER.info("跳转到登录页面");
        return "business/login";
    }

    /**
     * 处理登录逻辑
     * */
    @RequestMapping(value="/dologin")
    public Object doLogin(@Valid SysUser sysUser, BindingResult result, HttpServletRequest request){
        LOGGER.info("执行登录操作dologin，请求参数：{}",sysUser);
        //获取验证码
        String validateCode = (String)request.getSession().getAttribute(RandomValidateCodeUtil.RANDOMCODEKEY);
        if(!sysUser.getValidateCode().equals(validateCode)){
            LOGGER.info("验证码不匹配！请重新输入...");
            return "business/login";
        }
        /**检查是否已经登录*/
        Subject currentUser = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(sysUser.getUsername(),sysUser.getPassword(),request.getRemoteHost());
        token.setRememberMe(false);
        try {
            currentUser.login(token);
            LOGGER.info("{}登陆，成功", sysUser.getUsername());
            Session session = currentUser.getSession();
            SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
            session.setAttribute("username", user.getUsername());
            //session.setAttribute("roleId", user.getRoleId());
        }catch(Exception e){
            LOGGER.error(sysUser.getUsername() + "登陆失败", e);
        }
        /**如果身份已经校验过，则直接跳转到主页面*/
        if(currentUser.isAuthenticated()){
            return "redirect:/index";
        }else{

        }
        /**如果身份没有校验过，则跳转到登录页面*/
        return "business/login";
    }
    /**
     * 主页跳转
     * */
    @RequestMapping(value="/")
    public String index(){
        return "business/index";
    }



}
